package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class JavaCmd {
	
	public static void main(String[] args) throws IOException {
		new JavaCmd().startup();
	}
	
	private Process p = null;
	
	public void startup() {
		
		try {
			p = Runtime.getRuntime().exec("cmd");
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		
		new ConsoleReturn(p.getInputStream()).start();
		new ConsoleReturn(p.getErrorStream()).start();
		new ConsoleOutput(p.getOutputStream()).start();
	}
	
	private class ConsoleOutput extends Thread {
		private OutputStream os;
		public ConsoleOutput(OutputStream os) {
			this.os = os;
		}
		
		@Override
		public void run() {
			InputStream console = System.in;
			InputStreamReader reader = null;
			try {
				reader = new InputStreamReader(console,"GBK");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			BufferedReader br = new BufferedReader(reader);
			
			String cmd;
			PrintWriter pw = new PrintWriter(os);
			while(true) {
				try {
					cmd = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
				
				if(cmd.equals("exit")) {
					break;
				} else {
					pw.println(cmd);
					pw.flush();
				}
			}
			pw.close();
		}
	}
	
	private class ConsoleReturn extends Thread {
		private InputStream is;
		public ConsoleReturn(InputStream is) {
			this.is = is;
		}
		@Override
		public void run() {
			InputStreamReader reader = null;
			try {
				reader = new InputStreamReader(is,"GBK");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			char[] buf = new char[1024];
			int size;
			while(true) {
				try {
					size = reader.read(buf);
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
				if(size != -1) {
					System.out.print(new String(buf,0,size));
				} else {
					break;
				}
			}
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
